import { Button, message, Modal, Space } from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, ref } from 'vue'
import { omit } from 'xe-utils'

import { rechargeApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'
import { couponTypeOptions, refundStatusOptions } from '@/views/order/constants'

export default defineComponent({
  name: 'ElectricOrderManage',
  setup() {
    const { showConfirm } = useDialog()
    const switchLoading = ref(false)
    const switchValue = ref(0)
    const orderStatusOptions = [
      { label: '未支付', value: 0 },
      { label: '处理中', value: 1 },
      { label: '已成功', value: 2 },
      { label: '已完成', value: 3 },
      { label: '已作废', value: 4 },
      { label: '已退款', value: 5 },
      { label: '手动取消', value: 6 }
    ]

    const bynOrderStatusOptions = [
      { label: '充值成功', value: 2 },
      { label: '充值失败', value: 3 },
      { label: '退款成功', value: 4 },
      { label: '处理中', value: 11 },
      { label: '处理中', value: 10 }
    ]

    const isAutoStatusOptions = [
      { label: '是', value: 1 },
      { label: '否', value: 2 }
    ] as OptionItem[]

    const sourceOptions = [
      { label: '必应鸟', value: 0 },
      { label: '年年', value: 2 }
    ] as OptionItem[]

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        formConfig: {
          items: [
            {
              title: '订单编号',
              field: 'orderNo',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '缴费户号',
              field: 'account',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '充值金额',
              field: 'amount',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '订单状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: orderStatusOptions
              }
            },
            {
              title: '下单时间',
              field: 'timeRange',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['startTime', 'endTime']
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '订单号',
            field: 'orderNo',
            minWidth: 220
          },
          {
            title: '第三方订单号',
            field: 'tradeNo',
            minWidth: 220
          },
          {
            title: '微信支付流水号',
            field: 'wxTransactionId',
            minWidth: 220
          },
          {
            title: '订单状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return optionsToMap(orderStatusOptions)[cellValue]
            }
          },
          {
            title: '第三方状态',
            field: 'thirdStatus',
            minWidth: 120,
            formatter: ({ cellValue }) => {
              return optionsToMap(bynOrderStatusOptions)[cellValue]
            }
          },
          {
            title: '充值金额',
            field: 'productName',
            formatter: ({ cellValue }) => {
              return cellValue + '元'
            }
          },
          {
            title: '优惠券',
            minWidth: 120,
            slots: {
              default: 'couponName'
            }
          },
          {
            title: '实付金额',
            minWidth: 150,
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '下单人',
            field: 'nickname'
          },
          {
            title: '缴费户号',
            field: 'account',
            minWidth: 120
          },
          {
            title: '下单时间',
            field: 'orderTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 150
          },
          {
            title: '到账时间',
            field: 'accountDate',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 150
          },
          {
            title: '退款时间',
            field: 'refundTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 150
          },
          {
            title: '退款微信流水号',
            field: 'refundId',
            minWidth: 230
          },
          {
            title: '备注',
            field: 'reason',
            minWidth: 230
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 70
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              form = omit(form, ['timeRange'])
              const data = await rechargeApi.getElectricOrder({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                type: 1,
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //售后
    function handleAfterSales(row) {
      showConfirm({
        content: '是否确认售后，发起后将原路退款给到用户并生成新的售后订单？',
        onOk: async () => {
          try {
            await rechargeApi.ElectricOrderAfterSale(row.orderNo)
            tableRef.value.refresh()
            message.success('操作完成')
          } catch (error) {}
        }
      })
    }

    //完成充值
    function completeRecharge(row) {
      showConfirm({
        content: '是否确认更改状态？确认后，订单将不能再发起售后',
        onOk: async () => {
          try {
            await rechargeApi.finish(row.orderNo)
            tableRef.value.refresh()
            message.success('操作完成')
          } catch (error) {}
        }
      })
    }

    return {
      tableRef,
      tableConfig,
      switchLoading,
      switchValue,
      handleAfterSales,
      completeRecharge
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            couponName: ({ row }) => {
              if (row.couponName) {
                return <Space>{`${[row.couponName]} ${row.discount}折`}</Space>
              }
              return '无'
            },
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.price, row.gold)}</Space>
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  disabled={!row.hasAfterSale}
                  type="link"
                  size="small"
                  onClick={() => this.handleAfterSales(row)}
                >
                  售后
                </Button>
                {/* <Button
                  disabled={!(row.hasAfterSale && row.isManualRecharge != 1)}
                  type="link"
                  size="small"
                  onClick={() => this.completeRecharge(row)}
                >
                  更改状态
                </Button> */}
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
